/**
 * Created by PC on 2017/5/23.
 */
layui.use(['form', 'upload', 'jquery', 'layer', 'laytpl'], function () {
    var form = layui.form(),
        $ = layui.jquery,
        laytpl = layui.laytpl,
        divshow = parent.divshow,//header区提示信息
        layer = layui.layer;
    //联动对象
    var linkage = {};
    //渲染下拉框
    linkage.formRender = function (obj, tip) {
        $(obj).empty();
        $(obj).append('<option value="">' + tip + '</option>');
        form.render('select');
    };
    //读取数据库信息并写回到select框中（有数据已存在，可进行更改）
    linkage.readInit = function (obj, url, init,id) {
        axios.get(url)
            .then(function (res) {
                var array = res.data.data;
                var html = '';
                for (var i in array) {
                    html += '<option value=' + array[i].id + '>' + array[i].name + '</option>';
                }
                $(obj).append(html);
                form.render('select');
                // console.log(init);
                if (init)
                    $(obj).next().find('[lay-value="' + id + '"]').click();
            })
            .catch(function (res) {
                console.log(res);
            });
    };
    // 初始无数据存在，不可进行更改，只赋值
    linkage.read = function (obj, url) {
        axios.get(url)
            .then(function (res) {
                var array = res.data.data;
                var html = '';
                for (var i in array) {
                    html += '<option value=' + array[i].id + '>' + array[i].name + '</option>';
                }
                $(obj).append(html);
                form.render('select');
                // console.log(init);
                // if (init)
                //     $(obj).next().find('[lay-value="' + id + '"]').click();
            })
            .catch(function (res) {
                console.log(res);
            });
    };

    var university = 'form select[name=university]',
        school = 'form select[name=school]',
        department = 'form select[name=department]',
        major = 'form select[name=major]',
        clazz = 'form select[name=clazz]';

    var vm = new Vue({
        el: '#content'
        , data: {
            show: true
            ,showClass: true
            , user: {
                id: userid
            }
            , studentInfo: {
                userid:userid,
                classid:"",
                majorid:"",
                departmentid:"",
                schoolid:""
            }
            , attribution: {}
            , teacherInfoInternName: ""
            , teacherInfoPaperName: ""
        }
        , methods: {
            /**
             * 修改按钮
             */
            update: function () {
                vm.show = false;
                // vm.showClass = false;
                if(vm.user.state==2){
                    vm.showClass = true;
                }
                else if(vm.user.state ==1){
                    vm.showClass = false;
                }
                form.render('radio');
                form.render('select');
                $('#content input[type!=button]').attr("readOnly", false).removeClass("disabled");
                $('#content textarea').attr("readOnly", false).removeClass("disabled");
            },
            /**
             * 返回按钮
             */
            reload: function () {
                vm.show = true;
                vm.showClass = true;
                $('#content input[type!=button]').attr("readOnly", true).addClass("disabled");
                $('#content textarea').attr("readOnly", true).addClass("disabled");
                vm.getInfo(userid);
            },
            /**
             * 获取信息
             * @param userId
             */
            getInfo: function (userid) {
                $.ajax({
                    type: "GET",
                    url: "/student/findDetail/" + userid,
                    dataType: "json",
                    success: function (Response) {
                        console.log(Response);
                        vm.user = Response.data.user;
                        if (Response.data.studentInfo !== null) {
                            vm.studentInfo = Response.data.studentInfo;
                        }

                        // console.log(vm.studentInfo);
                        if (vm.studentInfo !== null && Response.data.clazz !== null) {
                            vm.attribution.universityName = Response.data.university.name;
                            vm.attribution.schoolName = Response.data.school.name;
                            vm.attribution.departmentName = Response.data.department.name;
                            vm.attribution.majorName = Response.data.major.name;
                            vm.attribution.clazzName = Response.data.clazz.name;
                        }
                        vm.teacherInfoInternName = Response.data.teacherInfoInternName;
                        vm.teacherInfoPaperName = Response.data.teacherInfoPaperName;
                        // console.log(vm.attribution);
                        // 读取大学
                        if ($(university).length) {
                            linkage.formRender(university, "选择大学");
                            if(Response.data.clazz!=null) {
                                linkage.readInit(university, '/university/findAll', Response.data.clazz, Response.data.clazz.universityid);
                            }
                            else{
                                linkage.read(university, '/university/findAll');
                            }
                            //读取学院
                            if ($(school).length) {
                                linkage.formRender(school, "选择学院");
                                form.on('select(university)', function (data) {
                                    linkage.formRender(school, "选择学院");
                                    linkage.formRender(department, "选择系");
                                    linkage.formRender(major, "选择专业");
                                    linkage.formRender(clazz, "选择班级");
                                    if(Response.data.clazz!=null) {
                                        linkage.readInit(school, '/school/findBath/' + data.value, Response.data.clazz, Response.data.clazz.schoolid);
                                    }
                                    else{
                                        linkage.read(school, '/school/findBath/' + data.value);
                                    }
                                });
                                if ($(department).length) {
                                    linkage.formRender(department, "选择学院");
                                    form.on('select(school)', function (data) {
                                        linkage.formRender(department, "选择系");
                                        linkage.formRender(major, "选择专业");
                                        linkage.formRender(clazz, "选择班级");
                                        if(Response.data.clazz!=null) {
                                            linkage.readInit(department, '/department/findBath/' + data.value, Response.data.clazz, Response.data.clazz.departmentid);
                                        }
                                        else{
                                            linkage.read(department, '/department/findBath/' + data.value);
                                        }
                                    });
                                    if ($(major).length) {
                                        linkage.formRender(school, "选择学院");
                                        linkage.formRender(department, "选择系");
                                        form.on('select(department)', function (data) {
                                            linkage.formRender(major, "选择专业");
                                            linkage.formRender(clazz, "选择班级");
                                            if(Response.data.clazz!=null) {
                                                linkage.readInit(major, '/major/findBath/' + data.value, Response.data.clazz, Response.data.clazz.majorid);
                                            }
                                            else{
                                                linkage.read(major, '/major/findBath/' + data.value);
                                            }
                                        });
                                        if ($(clazz).length) {
                                            linkage.formRender(school, "选择学院");
                                            linkage.formRender(department, "选择系");
                                            linkage.formRender(major, "选择专业");
                                            form.on('select(major)', function (data) {
                                                // console.log(data);
                                                linkage.formRender(clazz, "选择班级");
                                                if(Response.data.clazz!=null) {
                                                    linkage.readInit(clazz, '/class/findBatchByMajorid/' + data.value, Response.data.clazz, Response.data.clazz.id);
                                                }
                                                else{
                                                    linkage.read(clazz, '/class/findBatchByMajorid/' + data.value);
                                                }
                                            });
                                        }
                                    }
                                }

                            }
                        }
                    },
                    error: function (msg) {
                        console.log(vm.user.id);
                        console.log("失败");
                        console.log(msg);
                    }
                });
            }
        }
    });

    // 首次读取信息
    vm.getInfo(userid);
    $('#content input[type!=button]').addClass("disabled");
    $('#content textarea').addClass("disabled");

    //监听提交
    form.on('submit(save)', function () {
        vm.studentInfo.paperadvisor = null;
        vm.studentInfo.internadvisor = null;
        var url = "";
        var data = {
            user: vm.user
            , studentInfo: vm.studentInfo
        };
        console.log(data);
        if(vm.studentInfo.id == null) {
            vm.studentInfo.state = 1;
            url = "/student/addDetailOne";
        }
        else{
            url = "/student/modifyDetailOne";
        }
        axios.post(url, data)
            .then(function (response) {
                // console.log(response);
                if (response.data.success)
                    layer.msg("保存成功", {icon: 1, time: 1000}, function () {
                        //同时更新header区提示信息
                        getTips(userid, divshow);
                        vm.reload();
                    });
                else {
                    layer.msg(response.data.message, {icon: 2, time: 1000}, function () {
                        // vm.reload();
                    });
                }
            })
            .catch(function (response) {
                console.log(response);
            });
        return false;
    });

    //监听申请毕设指导老师按钮
    $("#applyPaper").click(function () {
        $.get('/student/addTeacher?schoolId='+vm.studentInfo.schoolid+
            '&teacherType=1',null,function (html) {
            layer.open({
                type:1,
                title:"选择指导老师",
                area:['600px','300px'],
                content:html,
                success:function (layero,index) {
                    // 监听教师
                    form.on('submit(saveTeacher)',function () {
                        vm.studentInfo.paperadvisor = $("#chooseTeacher").val();
                        axios.post('/student/modify',vm.studentInfo)
                            .then(function (response) {
                                console.log(response.data);
                                layer.msg('保存成功',{icon:1,time:1500},function () {
                                    vm.teacherInfoPaperName = $("#chooseTeacher").find('option:selected').text(); // 保存成功再进行表单数据的更新
                                    layer.close(index);
                                });
                            })
                            .catch(function (response) {
                                layer.msg("系统异常，保存失败",{icon: 5,time:1500},function () {
                                    layer.close(index);
                                });
                                console.log(response);
                            })
                        return false;
                    });
                    return false;
                },
                end:function (index) {
                    layer.close(index);
                }
            })
        });
    });

    //监听申请实习指导老师按钮
    $("#applyIntern").click(function () {
        $.get('/student/addTeacher?schoolId='+vm.studentInfo.schoolid+
            '&teacherType=2',null,function (html) {
            layer.open({
                type:1,
                title:"选择指导老师",
                area:['600px','300px'],
                content:html,
                success: function (layero,index) {
                    // 监听教师
                    form.on('submit(saveTeacher)',function () {
                        vm.studentInfo.internadvisor = $("#chooseTeacher").val();
                        vm.studentInfo.advisestate = 1;
                        vm.studentInfo.state = 1;
                        $.ajax({
                            type: "POST"
                            , url: "/student/modify"
                            , dataType: "json"
                            , contentType: "application/json"
                            , data: JSON.stringify(vm.studentInfo)
                            , success: function (response) {
                                console.log(response);
                                layer.msg('保存成功',{icon:1,time:1500},function () {
                                    vm.teacherInfoInternName = $("#chooseTeacher").find('option:selected').text();
                                    layer.close(index);
                                });
                            }
                            , error: function (msg) {
                                layer.msg('保存教师信息失败', {icon: 2, time: 1000});
                                console.log(msg);
                            }
                        });
                        return false;
                    });
                    return false;
                },
                end:function (index) {
                    layer.close(index);
                }
            })
        });
    });

    //监听radio
    form.on('radio(sex)', function (data) {
        // console.log(data);
        vm.user.sex = data.value;
    });

    //监听班级、专业、系、学院
    form.on('select(clazz)', function (data) {
        console.log(data);
        vm.studentInfo.classid = data.value;
        vm.studentInfo.majorid = $(major).val();
        vm.studentInfo.departmentid = $(department).val();
        vm.studentInfo.schoolid = $(school).val();
        console.log(vm.studentInfo);
    });
});